package com.jds.test.bio.p12;

import java.io.File;
import java.io.FileOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * https://www.cnblogs.com/silyvin/articles/12078621.html
 * https://www.cnblogs.com/silyvin/articles/12083466.html
 * Created by joyce on 2019/12/21.
 */
public class TcpClient {
    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    public static final int PORT = 12123;
    public static final int BUFFER_SIZE = 1024;

    public static void main(String []f) {

        Client client = new Client();
        run();
        Client.zuse();
    }

    /**
     * print 4059 稳定
     * lsof -p 12534 |wc -l 4558 不稳定
     */
    public static void run() {
        for(int i=0; i<5000; ++i) { // client 1 //100000 in linux
            try {
                new TcpClient().client();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public static void run2() {
        for(int i=0; i<100; ++i) { // client 2 100
            try {
                new TcpClient().client2();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }



    public void client() throws Exception {

        final String s2 = "localhost";
        Socket s = new Socket();
        s.connect(new InetSocketAddress(s2, PORT));

        // 连接成功后计数
        System.out.println(atomicInteger.incrementAndGet());
    }

    public void client2() throws Exception {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final String s2 = "localhost";
                    Socket s = new Socket();
                    s.connect(new InetSocketAddress(s2, PORT));

                    // 连接成功后计数
                    System.out.println(atomicInteger.incrementAndGet());
                    while (s.getInputStream().read(new byte[100]) != -1) {
                        ;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
